import CreateModal from '@/pages/Admin/Space/components/CreateModal';
import UpdateModal from '@/pages/Admin/Space/components/UpdateModal';
import {
  deleteSpaceUsingPost,
  listSpaceVoByPageUsingPost,
} from '@/services/backend/spaceController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Space, Tag, Typography} from 'antd';
import React, { useRef, useState } from 'react';
import {SPACE_LEVEL_COLOR_MAP, SPACE_LEVEL_MAP} from "@/constants/space";

/**
 * 用户管理页面
 *
 * @constructor
 */
const SpaceAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.SpaceVO>();
  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.SpaceVO) => {
    const hide = message.loading('正在删除');
    const ids: string[] = [row.id as any];
    const batchDeleteRequest: API.BatchDeleteRequest = {
      ids,
    };
    if (!row) return true;
    try {
      await deleteSpaceUsingPost(batchDeleteRequest);
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.SpaceVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '空间名称',
      dataIndex: 'spaceName',
      valueType: 'text',
    },
    {
      title: '空间级别',
      dataIndex: 'spaceLevel',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '普通版',
          status: 'Success',
        },
        1: {
          text: '专业版',
          status: 'Success',
        },
        2: {
          text: '旗舰版',
          status: 'Error',
        },
      },
      render: (_, record) => (
        <Space>
          {
            <Tag color={SPACE_LEVEL_COLOR_MAP[record.spaceLevel??0]} key={record.spaceLevel}>
              {SPACE_LEVEL_MAP[record.spaceLevel??0]}
            </Tag>
          }
        </Space>
      )
    },
    {
      title: '最大数量',
      dataIndex: 'maxCount',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '最小数量',
      dataIndex: 'maxSize',
      valueType: 'text',
      ellipsis: true,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '图片总数',
      dataIndex: 'totalCount',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '空间大小',
      dataIndex: 'totalSize',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '空间创建人',
      dataIndex: ['user', 'userAccount'],
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            <Space>修改</Space>
          </a>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <ProTable<API.SpaceVO>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        // toolBarRender={() => [
        //   <Button
        //     type="primary"
        //     key="primary"
        //     onClick={() => {
        //       setCreateModalVisible(true);
        //     }}
        //   >
        //     <PlusOutlined /> 创建空间
        //   </Button>,
        // ]}
        request={async (params, sort, filter) => {
          const sortField: any = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listSpaceVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.SpaceQueryRequest);
          console.log(params, sort, filter);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreateModal
        id={currentRow?.id}
        visible={createModalVisible}
        onSubmit={() => {
          setCreateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        columns={columns}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </div>
  );
};
export default SpaceAdminPage;
